package com.easyattendance.services;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;

import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.SQLQuery;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.easyattendance.model.Class;
import com.easyattendance.model.ClassUser;
import com.easyattendance.model.Proxy;
import com.easyattendance.model.Teacher;
import com.easyattendance.model.TimeSlot;
import com.easyattendance.model.TimeTable;
import com.easyattendance.util.HibernateUtil;

public class AddProxyService {

	/* Method to CREATE a proxy record in the database */
	   public synchronized boolean addProxy(Proxy proxy){
	      Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      boolean result=false;
	      
	      try{
	         tx = session.beginTransaction();

	         session.save(proxy);
	        	 
	         tx.commit();
	         result=true;
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	     return result;
	   }
	   
	   public boolean ifAlreadyExists(Proxy proxy) {
			 boolean flag = false;
			 
			 Session session = HibernateUtil.openSession();
		      Transaction tx = null;
		      List proxyList = null;
		      try{
		         tx = session.beginTransaction();
		         proxyList = session.createQuery("FROM Proxy").list(); 
		         for (Iterator iterator = proxyList.iterator(); iterator.hasNext();){
		        	 Proxy tempProxy = (Proxy) iterator.next(); 
		            if(tempProxy.equals(proxy)) {
		            	System.out.println("Proxy already assigned");
		            	flag = true;
		            	break;
		            }
		             
		         }
		         tx.commit();
		      }catch (HibernateException e) {
		         if (tx!=null) tx.rollback();
		         e.printStackTrace(); 
		      }finally {
		         session.close(); 
		      }
			 
			 return flag;
		}
	   
	/* Get day from date entered */
	public String getDayFromDate(Date date) {
		int DAY = date.getDay();
		String day;
		
		switch (DAY) {
		case 1:
			day = "Monday";
			break;
		case 2:
			day = "Tuesday";
			break;
		case 3:
			day = "Wednesday";
			break;
		case 4:
			day = "Thrusday";
			break;
		case 5:
			day = "Friday";
			break;
		case 6:
			day = "Saturday";
			break;
		default:
			day = "None";
			break;

		}
		return day;
	}
	
	 /* Method to  READ all the proxy timeslot values  for particular teacher for that day */
	   public String[] getTeacherWiseProxySlots(String teacherEmailId,String today) {
		   Session session = HibernateUtil.openSession();
		   
		   AddTeacherService teacherService = new AddTeacherService();
		   String teacherId = teacherService.getTeacherByEmailId(teacherEmailId).getTeacher_id();
				   
	      Transaction tx = null;
	      List proxySlots = null;
	      String[] proxySlotsMap = new String[10];
	      TimeSlot timeSlotsSettings = null;
	      
	      int i = 0;
	      try{
	         tx = session.beginTransaction();
	         proxySlots = session.createQuery("FROM Proxy where proxy_teacher_id='"+teacherId+"' and proxy_date='"+today+"'").list();
	         
	         for (Iterator iterator =proxySlots.iterator(); iterator.hasNext();){
	        	 Proxy proxy_teacher = (Proxy) iterator.next();
	        	  proxySlotsMap[i++] = proxy_teacher.getTime_slot();
	        	 System.out.print(" proxy timeslot: " + proxy_teacher.getTime_slot());
	         }
	         tx.commit();
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      return proxySlotsMap;
	   }

	   public String getSubjectByTimeSlot(String proxySlot, String emailId) {
			//String[] days = { "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday" };
			String subject= new String();
			
			AddTeacherService teacherService = new AddTeacherService();
			String teacherId = teacherService.getTeacherByEmailId(emailId).getTeacher_id();
			Session session = HibernateUtil.openSession();
			Transaction tx = null;
			String tmpTime = null;

			try {
				tx = session.beginTransaction();
				
				//for(int i=0; i<timeSlots.length - 1; i++) {
					//tmpTime = timeSlots[i];
						SQLQuery query=session.createSQLQuery("select proxy_subject_id from tbl_proxy where proxy_teacher_id='"+teacherId+"' and time_slot='"+proxySlot+"'");
						subject = (String) query.uniqueResult();
						System.out.println("Proxy Teacher subject: "+subject);
				//}
			
			tx.commit();

			} catch (HibernateException e) {
				if (tx != null)
					tx.rollback();
				e.printStackTrace();
			} finally {
				session.close();
			}
			return subject;
			}
	   
	   
	 /*  public String[] getTeacherWiseProxySlots(Date[] timeSlots, String emailId) {
			//String[] days = { "Monday", "Tuesday", "Wednesday", "Thrusday", "Friday", "Saturday" };
			String[] slots= new String[10];
			AddTeacherService teacherService = new AddTeacherService();
			String teacherId = teacherService.getTeacherByEmailId(emailId).getTeacher_id();
			
			Session session = HibernateUtil.openSession();
			Transaction tx = null;

			try {
				tx = session.beginTransaction();                                                                                                       
				Date tmpTime=null;
				for(int t=0; t<timeSlots.length; t++) {
						//tmpTime = "2013-10-10 "+timeSlots[t]+":00";
						tmpTime = timeSlots[t];
						
						Query query=session.createQuery("from Proxy where proxy_teacher_id='"+teacherId+" and time_slot='"+tmpTime+"'");
						slots[t] = (String) query.uniqueResult();
						
						System.out.println("time slot: "+slots[t]);
				}
			
			
			tx.commit();

			} catch (HibernateException e) {
				if (tx != null)
					tx.rollback();
				e.printStackTrace();
			} finally {
				session.close();
			}
			return slots;
			} */

	   /* Method to  READ the proxy that is occupied on a day for a timeslot in a semester */
	   public Proxy getProxyOnDayForTimeSlot(String day, String timeSlot, String ClassId, String subjectId) {
		   Session session = HibernateUtil.openSession();
	      Transaction tx = null;
	      
	      Proxy proxy = null;
	      AddTeacherService teacherService = new AddTeacherService();
	      AddClassService ClassService = new AddClassService();
	      try{
	         tx = session.beginTransaction();
	         //String deptId = teacherService.getDeptIdByTeacherId(teacherEmail);
	         String deptId = ClassService.getClassById(ClassId).getSection().getSection_id();
	         
	         SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	         
	         String tempSlot="2013-10-10 "+timeSlot+":00";
	        
	         Query query = session.createQuery("FROM Proxy where proxy_date ='"+new Date()+"' and time_slot='"+tempSlot+"'"
	         		+ " and section_id='"+deptId+"' and class_id='"+ClassId+"' and subject_id='"+subjectId+"'");
	         proxy = (Proxy) query.uniqueResult();
	         
	         tx.commit();
	      }catch (HibernateException e) {
	         if (tx!=null) tx.rollback();
	         e.printStackTrace(); 
	      }finally {
	         session.close(); 
	      }
	      if(proxy == null) {
	    	  return null;
	        }
	      else {
	    	  return proxy;
	      }
	      
	   }
}

